﻿using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Web.Mvc;
using System.Web.Routing;

namespace LAPI.Web.Helpers
{
    public static class TextBoxExtension
    {
        public static MvcHtmlString TextBoxFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, object htmlAttributes)
        {
            return TextBoxFor(html, expression, new RouteValueDictionary(htmlAttributes));
        }

        public static MvcHtmlString TextBoxFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, IDictionary<string, object> htmlAttributes)
        {
            ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
            string htmlFieldName = ExpressionHelper.GetExpressionText(expression);

            TagBuilder tag = new TagBuilder("input");
            tag.MergeAttributes(htmlAttributes);
            
            switch (metadata.DataTypeName)
            {
                case "Password":
                    {
                        tag.Attributes.Add("type", "password");
                        break;
                    }
                default:
                    {
                        tag.Attributes.Add("type", "text");
                    }
                    break;
            }            
            tag.Attributes.Add("id",htmlFieldName);
            tag.Attributes.Add("name", htmlFieldName);
            
            if (!tag.Attributes.ContainsKey("value"))
                tag.Attributes.Add("value", "");

            return MvcHtmlString.Create(tag.ToString(TagRenderMode.Normal));
        }
    }
}